Self-Driving Car Engineer Nanodegree

Deep Learning

Project: Build a Traffic Sign Recognition Classifier

In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary.

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing the code template and writeup template will cover all of the rubric points for this project.

The rubric contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.


Step 0: Load The Data

In [1]:
# Load pickled data
import pickle

# TODO: Fill this in based on where you saved the training and testing data

training_file = 'train.p'
validation_file= 'valid.p'
testing_file = 'test.p'

with open(training_file, mode='rb') as f:
    train = pickle.load(f)
with open(validation_file, mode='rb') as f:
    valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
    test = pickle.load(f)
    
X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test = test['features'], test['labels']

Step 1: Dataset Summary & Exploration

The pickled data is a dictionary with 4 key/value pairs:

  • 'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).
  • 'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.
  • 'sizes' is a list containing tuples, (width, height) representing the the original width and height the image.
  • 'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGES

Complete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the pandas shape method might be useful for calculating some of the summary results.

Provide a Basic Summary of the Data Set Using Python, Numpy and/or Pandas

In [2]:
### Replace each question mark with the appropriate value. 
### Use python, pandas or numpy methods rather than hard coding the results

# TODO: Number of training examples
n_train = format(len(X_train))

# TODO: Number of testing examples.
n_test = format(len(X_test))

n_valid = format(len(X_valid))

# TODO: What's the shape of an traffic sign image?
image_shape = format(X_train[0].shape)

# TODO: How many unique classes/labels there are in the dataset.
n_classes = len(set(y_train))

print("Number of training examples =", n_train)
print("Number of testing examples =", n_test)
print("Number of validation examples = ", n_valid)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
Number of training examples = 34799
Number of testing examples = 12630
Number of validation examples =  4410
Image data shape = (32, 32, 3)
Number of classes = 43

Include an exploratory visualization of the dataset

Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.

The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.

NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections.

In [3]:
### Data exploration visualization code goes here.
### Feel free to use as many code cells as needed.

import matplotlib.pyplot as plt
# Visualizations will be shown in the notebook.
%matplotlib inline

import random
import cv2
import numpy as np
import pandas as pd

signnames = pd.read_csv('signnames.csv')
label_set = dict()

for element in signnames.iterrows():  # iterate every row

    r = element[1]
    ClassId = r['ClassId']
    SignName = r['SignName']
    label_set[ClassId] = SignName
    
sample = np.random.randint(0, np.shape(X_train)[0], 6)
sample_images = X_train[sample]
sample_labels = [label_set[s] for s in  y_train[sample]]

fig, axes = plt.subplots(3,2, figsize=(15, 15))
axes = axes.ravel()

# show traffic signs
for axis, img, label in zip(axes.ravel(), sample_images, sample_labels):

    axis.axis('off')
    axis.set_title(label)
    axis.imshow(img)

plt.show()

# prepare statistic data

train_classes, train_counts = np.unique(y_train, return_counts=True)
dict_train_classes = dict(zip(train_classes, train_counts))
test_classes, test_counts = np.unique(y_test, return_counts=True)
dict_test_classes = dict(zip(test_classes, test_counts))

# show statistics

plt.figure(figsize=(12, 5))
plt.bar(range(len(dict_train_classes)), dict_train_classes.values(), width=0.8, label="train", color="b")
plt.bar(range(len(dict_test_classes)), dict_test_classes.values(), width=0.8, label="test", color="g")
plt.legend(loc="best")
plt.title('Class Frequency')
plt.xlabel('Classes')
plt.ylabel('Frequency')
plt.show()

Step 2: Design and Test a Model Architecture

Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.

There are various aspects to consider when thinking about this problem:

  • Neural network architecture
  • Play around preprocessing techniques (normalization, rgb to grayscale, etc)
  • Number of examples per label (some have more than others).
  • Generate fake data.

Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.

NOTE: The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!

Pre-process the Data Set (normalization, grayscale, etc.)

Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.

In [4]:
### Preprocess the data here. Preprocessing steps could include normalization, converting to grayscale, etc.
### Feel free to use as many code cells as needed.


def resize(image):
    
    return cv2.resize(image, (32, 32))


def normalize(image):
    # return cv2.normalize(image, zeros, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)
    return (np.array(image) - 128.0 ) /128.0
    

def grayscale(image):

    return cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)


def equalize(image):
    
    image_yuv = cv2.cvtColor(image, cv2.COLOR_BGR2YUV)
    image_yuv[:,:,0] = cv2.equalizeHist(image_yuv[:,:,0])  # equalize the histogram of the Y channel
    
    return cv2.cvtColor(image_yuv, cv2.COLOR_YUV2BGR)  # convert the YUV image back to RGB format and return image


def equalize_images(images):
    
    for i in range(len(images)):
    
        images[i] = equalize(images[i])
        
    return images


# equalize train images
X_train = equalize_images(X_train)
X_valid = equalize_images(X_valid)
X_test = equalize_images(X_test)
    
# equalize sample images
sample_images = equalize_images(sample_images)

# show traffic signs after equalizing them
fig, axes = plt.subplots(3,2, figsize=(15, 15))
axes = axes.ravel()

for axis, img, label in zip(axes.ravel(), sample_images, sample_labels):

    axis.axis('off')
    axis.set_title(label)
    axis.imshow(img)

plt.show()

Model Architecture

In [5]:
### Define your architecture here.
### Feel free to use as many code cells as needed.


import tensorflow as tf
from tensorflow.contrib.layers import flatten

EPOCHS = 50
BATCH_SIZE = 128

keep_prob = tf.placeholder(tf.float32)


def LeNet(x):    

    # Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer
    mu = 0
    sigma = 0.1
    
    # SOLUTION: Layer 1: Convolutional. Input = 32x32x1. Output = 28x28x6.
    conv1_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 3, 6), mean = mu, stddev = sigma))
    conv1_b = tf.Variable(tf.zeros(6))
    conv1   = tf.nn.conv2d(x, conv1_W, strides=[1, 1, 1, 1], padding='VALID') + conv1_b

    # SOLUTION: Activation.
    conv1 = tf.nn.relu(conv1)

    # SOLUTION: Pooling. Input = 28x28x6. Output = 14x14x6.
    conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')

    # SOLUTION: Layer 2: Convolutional. Output = 10x10x16.
    conv2_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 6, 16), mean = mu, stddev = sigma))
    conv2_b = tf.Variable(tf.zeros(16))
    conv2   = tf.nn.conv2d(conv1, conv2_W, strides=[1, 1, 1, 1], padding='VALID') + conv2_b
    
    # SOLUTION: Activation.
    conv2 = tf.nn.relu(conv2)

    # SOLUTION: Pooling. Input = 10x10x16. Output = 5x5x16.
    conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')

    # SOLUTION: Flatten. Input = 5x5x16. Output = 400.
    fc0   = flatten(conv2)
    
    # SOLUTION: Layer 3: Fully Connected. Input = 400. Output = 120.
    fc1_W = tf.Variable(tf.truncated_normal(shape=(400, 120), mean = mu, stddev = sigma))
    fc1_b = tf.Variable(tf.zeros(120))
    fc1   = tf.matmul(fc0, fc1_W) + fc1_b
    fc1   = tf.nn.dropout(fc1, keep_prob)
    
    # SOLUTION: Activation.
    fc1    = tf.nn.relu(fc1)

    # SOLUTION: Layer 4: Fully Connected. Input = 120. Output = 84.
    fc2_W  = tf.Variable(tf.truncated_normal(shape=(120, 84), mean = mu, stddev = sigma))
    fc2_b  = tf.Variable(tf.zeros(84))
    fc2    = tf.matmul(fc1, fc2_W) + fc2_b
    fc2 = tf.nn.dropout(fc2, keep_prob)
    
    # SOLUTION: Activation.
    fc2    = tf.nn.relu(fc2)

    # SOLUTION: Layer 5: Fully Connected. Input = 84. Output = n_classes = 43.
    fc3_W  = tf.Variable(tf.truncated_normal(shape=(84, n_classes), mean = mu, stddev = sigma))
    fc3_b  = tf.Variable(tf.zeros(n_classes))
    logits = tf.matmul(fc2, fc3_W) + fc3_b
    
    return logits


# Features and Labels

x = tf.placeholder(tf.float32, (None, 32, 32, 3))
y = tf.placeholder(tf.int32, (None))
one_hot_y = tf.one_hot(y, n_classes)


# Training Pipeline

rate = 0.001

logits = LeNet(x)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits, one_hot_y)
loss_operation = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate = rate)
training_operation = optimizer.minimize(loss_operation)


# Model Evaluation

correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
saver = tf.train.Saver()


def evaluate(X_data, y_data):
    num_examples = len(X_data)
    total_accuracy = 0
    sess = tf.get_default_session()

    for offset in range(0, num_examples, BATCH_SIZE):

        batch_x, batch_y = X_data[offset: offset + BATCH_SIZE], y_data[offset: offset + BATCH_SIZE]
        accuracy = sess.run(accuracy_operation, feed_dict = {x: batch_x, y: batch_y, keep_prob: 1.0})
        total_accuracy += (accuracy * len(batch_x))

    return total_accuracy / num_examples

Train, Validate and Test the Model

A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation sets imply underfitting. A high accuracy on the test set but low accuracy on the validation set implies overfitting.

In [6]:
### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected, 
### the accuracy on the test set should be calculated and reported as well.
### Feel free to use as many code cells as needed.


# Prepare data set
X_train = normalize(X_train)

# Split Data into Training, Validation and Testing Sets

from sklearn.model_selection import train_test_split

X_train, X_validation, y_train, y_validation = train_test_split(X_train, y_train, test_size = 0.2)

print()
print("Training Set:    {} samples".format(len(X_train)))
print("Validation Set:  {} samples".format(len(X_validation)))
print("Test Set:        20 %")


# Train the Model

from sklearn.utils import shuffle

train_accuracies = []
validation_accuracies = []

with tf.Session() as sess:

    sess.run(tf.global_variables_initializer())
    num_examples = len(X_train)
    
    print()
    print("Training...")
    print()

    for i in range(EPOCHS):

        X_train, y_train = shuffle(X_train, y_train)

        for offset in range(0, num_examples, BATCH_SIZE):

            end = offset + BATCH_SIZE
            batch_x, batch_y = X_train[offset:end], y_train[offset:end]
            sess.run(training_operation, feed_dict={x: batch_x, y: batch_y, keep_prob:0.5})
            
        validation_accuracy = evaluate(X_validation, y_validation)
        validation_accuracies.append(validation_accuracy)
        
        train_accuracy = evaluate(X_train, y_train)
        train_accuracies.append(train_accuracy)

        print("EPOCH {} ...".format(i+1))
        print("Validation Accuracy = {:.3f}".format(validation_accuracy))
        print("Train Accuracy = {:.3f}".format(train_accuracy))
        print()
        
    saver.save(sess, './lenet')
    print("Model saved")


# Evaluate the Model

with tf.Session() as sess:

    saver.restore(sess, tf.train.latest_checkpoint('.'))

    test_accuracy = evaluate(X_test, y_test)
    print()
    print("Test Accuracy = {:.3f}".format(test_accuracy))

# plot accuracies

plt.plot(validation_accuracies, label="validation")
plt.plot(train_accuracies, label="train")
plt.legend(bbox_to_anchor=(1, 0.25))
plt.title("Accuracy")
plt.show()
Training Set:    27839 samples
Validation Set:  6960 samples
Test Set:        20 %

Training...

EPOCH 1 ...
Validation Accuracy = 0.658
Train Accuracy = 0.660

EPOCH 2 ...
Validation Accuracy = 0.826
Train Accuracy = 0.835

EPOCH 3 ...
Validation Accuracy = 0.883
Train Accuracy = 0.891

EPOCH 4 ...
Validation Accuracy = 0.911
Train Accuracy = 0.919

EPOCH 5 ...
Validation Accuracy = 0.929
Train Accuracy = 0.941

EPOCH 6 ...
Validation Accuracy = 0.938
Train Accuracy = 0.951

EPOCH 7 ...
Validation Accuracy = 0.947
Train Accuracy = 0.959

EPOCH 8 ...
Validation Accuracy = 0.953
Train Accuracy = 0.968

EPOCH 9 ...
Validation Accuracy = 0.959
Train Accuracy = 0.973

EPOCH 10 ...
Validation Accuracy = 0.966
Train Accuracy = 0.978

EPOCH 11 ...
Validation Accuracy = 0.966
Train Accuracy = 0.979

EPOCH 12 ...
Validation Accuracy = 0.969
Train Accuracy = 0.982

EPOCH 13 ...
Validation Accuracy = 0.969
Train Accuracy = 0.982

EPOCH 14 ...
Validation Accuracy = 0.973
Train Accuracy = 0.985

EPOCH 15 ...
Validation Accuracy = 0.975
Train Accuracy = 0.988

EPOCH 16 ...
Validation Accuracy = 0.977
Train Accuracy = 0.990

EPOCH 17 ...
Validation Accuracy = 0.977
Train Accuracy = 0.989

EPOCH 18 ...
Validation Accuracy = 0.977
Train Accuracy = 0.991

EPOCH 19 ...
Validation Accuracy = 0.977
Train Accuracy = 0.990

EPOCH 20 ...
Validation Accuracy = 0.980
Train Accuracy = 0.992

EPOCH 21 ...
Validation Accuracy = 0.981
Train Accuracy = 0.993

EPOCH 22 ...
Validation Accuracy = 0.978
Train Accuracy = 0.994

EPOCH 23 ...
Validation Accuracy = 0.980
Train Accuracy = 0.994

EPOCH 24 ...
Validation Accuracy = 0.981
Train Accuracy = 0.995

EPOCH 25 ...
Validation Accuracy = 0.981
Train Accuracy = 0.994

EPOCH 26 ...
Validation Accuracy = 0.982
Train Accuracy = 0.995

EPOCH 27 ...
Validation Accuracy = 0.981
Train Accuracy = 0.995

EPOCH 28 ...
Validation Accuracy = 0.983
Train Accuracy = 0.996

EPOCH 29 ...
Validation Accuracy = 0.985
Train Accuracy = 0.997

EPOCH 30 ...
Validation Accuracy = 0.984
Train Accuracy = 0.997

EPOCH 31 ...
Validation Accuracy = 0.984
Train Accuracy = 0.997

EPOCH 32 ...
Validation Accuracy = 0.984
Train Accuracy = 0.997

EPOCH 33 ...
Validation Accuracy = 0.986
Train Accuracy = 0.997

EPOCH 34 ...
Validation Accuracy = 0.984
Train Accuracy = 0.997

EPOCH 35 ...
Validation Accuracy = 0.984
Train Accuracy = 0.998

EPOCH 36 ...
Validation Accuracy = 0.984
Train Accuracy = 0.998

EPOCH 37 ...
Validation Accuracy = 0.984
Train Accuracy = 0.997

EPOCH 38 ...
Validation Accuracy = 0.987
Train Accuracy = 0.998

EPOCH 39 ...
Validation Accuracy = 0.987
Train Accuracy = 0.998

EPOCH 40 ...
Validation Accuracy = 0.986
Train Accuracy = 0.998

EPOCH 41 ...
Validation Accuracy = 0.987
Train Accuracy = 0.999

EPOCH 42 ...
Validation Accuracy = 0.986
Train Accuracy = 0.998

EPOCH 43 ...
Validation Accuracy = 0.985
Train Accuracy = 0.998

EPOCH 44 ...
Validation Accuracy = 0.986
Train Accuracy = 0.999

EPOCH 45 ...
Validation Accuracy = 0.987
Train Accuracy = 0.999

EPOCH 46 ...
Validation Accuracy = 0.986
Train Accuracy = 0.998

EPOCH 47 ...
Validation Accuracy = 0.986
Train Accuracy = 0.999

EPOCH 48 ...
Validation Accuracy = 0.988
Train Accuracy = 0.999

EPOCH 49 ...
Validation Accuracy = 0.987
Train Accuracy = 0.999

EPOCH 50 ...
Validation Accuracy = 0.987
Train Accuracy = 0.999

Model saved

Test Accuracy = 0.909

Step 3: Test a Model on New Images

To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.

You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.

Load and Output the Images

In [7]:
### Load the images and plot them here.
### Feel free to use as many code cells as needed.

test = np.random.randint(0, np.shape(X_valid)[0], 30)
test_images = X_valid[test]
test_labels = [label_set[s] for s in  y_valid[test]]

resized_images = []

fig, axes = plt.subplots(10,3, figsize=(10, 30))
axes = axes.ravel()

for axis, img, label in zip(axes.ravel(), test_images, test_labels):

    resized_image = resize(img)  # resize image
    resized_images.append(resized_image)

    axis.axis('off')
    axis.set_title(label)
    axis.imshow(img)   # let's output images once again

normalized_images = normalize(resized_images)  # normalize images

Predict the Sign Type for Each Image

In [8]:
### Run the predictions here and use the model to output the prediction for each image.
### Make sure to pre-process the images with the same pre-processing pipeline used earlier.
### Feel free to use as many code cells as needed.

with tf.Session() as sess:
    
    saver.restore(sess, './lenet')  
    softmax_logits = tf.nn.softmax(logits)
    top_k = tf.nn.top_k(softmax_logits, k=5)
    softmax_logits = sess.run(softmax_logits, feed_dict={x: normalized_images, keep_prob: 1.0})
    my_top_k = sess.run(top_k, feed_dict={x: normalized_images, keep_prob: 1.0})
    top_5 = sess.run(top_k, feed_dict={x: normalized_images, keep_prob: 1.0})
    

# Predict probability considering top_5

fig, axes = plt.subplots(len(resized_images), 6, figsize=(15, 80))
axes = axes.ravel()

for i, image in enumerate(resized_images):
    
    axes[6 * i].axis('off')
    axes[6 * i].imshow(image)
    axes[6 * i].set_title('input')

    axes[6 * i + 1].axis('off')
    axes[6 * i + 1].imshow(X_valid[np.argwhere(y_valid == top_5[1][i][0])[0]].squeeze())
    axes[6 * i + 1].set_title('1. top: {} ({:.0f}%)'.format(top_5[1][i][0], 100 * top_5[0][i][0]))
    
    axes[6 * i + 2].axis('off')
    axes[6 * i + 2].imshow(X_valid[np.argwhere(y_valid == top_5[1][i][1])[0]].squeeze())
    axes[6 * i + 2].set_title('2. top: {} ({:.0f}%)'.format(top_5[1][i][1], 100 * top_5[0][i][1]))

    axes[6 * i + 3].axis('off')
    axes[6 * i + 3].imshow(X_valid[np.argwhere(y_valid == top_5[1][i][2])[0]].squeeze())
    axes[6 * i + 3].set_title('3. top: {} ({:.0f}%)'.format(top_5[1][i][2], 100 * top_5[0][i][2]))
    
    axes[6 * i + 4].axis('off')
    axes[6 * i + 4].imshow(X_valid[np.argwhere(y_valid == top_5[1][i][3])[0]].squeeze())
    axes[6 * i + 4].set_title('4. top: {} ({:.0f}%)'.format(top_5[1][i][3], 100 * top_5[0][i][3]))
    
    axes[6 * i + 5].axis('off')
    axes[6 * i + 5].imshow(X_valid[np.argwhere(y_valid == top_5[1][i][4])[0]].squeeze())
    axes[6 * i + 5].set_title('5. top: {} ({:.0f}%)'.format(top_5[1][i][4], 100 * top_5[0][i][4]))

Analyze Performance

In [9]:
### Calculate the accuracy for these new images. 
### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.

fig, axis = plt.subplots(30, 2, figsize = (10, 100))
axis = axis.ravel()

for i in range(len(softmax_logits) * 2):
    
    if i % 2 == 0:
        
        axis[i].axis('off')
        axis[i].set_title(test_labels[i // 2])
        axis[i].imshow(resized_images[i // 2])
        
    else:
        
        axis[i].bar(np.arange(n_classes), softmax_logits[(i - 1) // 2]) 
        axis[i].set_ylabel('Probability')

Output Top 5 Softmax Probabilities For Each Image Found on the Web

For each of the new images, print out the model's softmax probabilities to show the certainty of the model's predictions (limit the output to the top 5 probabilities for each image). tf.nn.top_k could prove helpful here.

The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.

tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.

Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. tk.nn.top_k is used to choose the three classes with the highest probability:

# (5, 6) array
a = np.array([[ 0.24879643,  0.07032244,  0.12641572,  0.34763842,  0.07893497,
         0.12789202],
       [ 0.28086119,  0.27569815,  0.08594638,  0.0178669 ,  0.18063401,
         0.15899337],
       [ 0.26076848,  0.23664738,  0.08020603,  0.07001922,  0.1134371 ,
         0.23892179],
       [ 0.11943333,  0.29198961,  0.02605103,  0.26234032,  0.1351348 ,
         0.16505091],
       [ 0.09561176,  0.34396535,  0.0643941 ,  0.16240774,  0.24206137,
         0.09155967]])

Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:

TopKV2(values=array([[ 0.34763842,  0.24879643,  0.12789202],
       [ 0.28086119,  0.27569815,  0.18063401],
       [ 0.26076848,  0.23892179,  0.23664738],
       [ 0.29198961,  0.26234032,  0.16505091],
       [ 0.34396535,  0.24206137,  0.16240774]]), indices=array([[3, 0, 5],
       [0, 1, 4],
       [0, 5, 1],
       [1, 3, 5],
       [1, 4, 3]], dtype=int32))

Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.

In [10]:
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web. 
### Feel free to use as many code cells as needed.

print()
print("See top_5 under previous prediction, here TopKV2:")
print()

print(top_5)
See top_5 under previous prediction, here TopKV2:

TopKV2(values=array([[  1.00000000e+00,   1.51558369e-14,   1.02367532e-15,
          3.02895187e-20,   3.39237998e-21],
       [  1.00000000e+00,   2.29209789e-08,   2.12734223e-11,
          7.46917935e-13,   5.57737721e-13],
       [  1.00000000e+00,   5.62246118e-28,   2.05900656e-33,
          0.00000000e+00,   0.00000000e+00],
       [  1.00000000e+00,   7.78312692e-11,   6.10918000e-13,
          2.17537949e-14,   2.13190858e-14],
       [  9.99597132e-01,   3.77884164e-04,   1.66183600e-05,
          4.67078326e-06,   2.96746430e-06],
       [  1.00000000e+00,   1.58062224e-12,   2.55698782e-14,
          7.33007151e-15,   4.00180462e-15],
       [  9.99957561e-01,   3.50658411e-05,   4.17266483e-06,
          3.14969247e-06,   6.76260825e-08],
       [  1.00000000e+00,   1.32922048e-13,   3.51762248e-16,
          1.77091177e-16,   4.42869191e-18],
       [  1.00000000e+00,   1.24771703e-11,   3.82469892e-16,
          3.33053986e-19,   3.00504765e-20],
       [  1.00000000e+00,   2.56830173e-15,   3.95489874e-21,
          1.14155210e-23,   2.06671105e-25],
       [  1.00000000e+00,   2.70083245e-09,   5.90087311e-12,
          7.75499402e-13,   4.41787042e-13],
       [  1.00000000e+00,   2.14141153e-11,   5.83651271e-15,
          7.05648755e-18,   6.11266124e-18],
       [  1.00000000e+00,   1.09299634e-18,   4.59686526e-24,
          9.25119309e-26,   5.91057485e-26],
       [  9.99975204e-01,   2.36361593e-05,   1.17342427e-06,
          4.77910822e-09,   1.25652366e-09],
       [  1.00000000e+00,   3.09815339e-22,   8.75437311e-27,
          2.88698065e-30,   5.20622745e-32],
       [  1.00000000e+00,   3.17996163e-09,   2.00803019e-09,
          1.97165725e-16,   1.68507173e-16],
       [  1.00000000e+00,   1.23294033e-08,   8.94197960e-09,
          1.79094142e-10,   1.39296547e-10],
       [  1.00000000e+00,   3.05841710e-14,   9.57648992e-16,
          7.24396804e-19,   6.75691014e-20],
       [  9.85471129e-01,   1.40596721e-02,   2.08782047e-04,
          1.07766449e-04,   5.65875453e-05],
       [  9.99944687e-01,   5.52660713e-05,   3.24463859e-11,
          2.88558812e-11,   5.90562451e-12],
       [  1.00000000e+00,   3.42874383e-13,   6.19863369e-16,
          2.42675310e-16,   7.35044169e-19],
       [  1.00000000e+00,   6.94815559e-23,   5.40850547e-23,
          1.05348548e-24,   2.98137037e-25],
       [  1.00000000e+00,   9.28287124e-14,   4.97419624e-14,
          2.64275838e-14,   3.13595229e-15],
       [  1.00000000e+00,   3.59944630e-09,   1.17527594e-11,
          5.15403388e-12,   2.15695474e-12],
       [  9.31767404e-01,   3.37213315e-02,   1.70594379e-02,
          9.42305848e-03,   4.85701580e-03],
       [  9.99711931e-01,   2.87000381e-04,   4.69635864e-07,
          1.73975536e-07,   1.73019174e-07],
       [  9.99999881e-01,   4.53776892e-08,   4.10774348e-08,
          3.08098969e-09,   5.12339948e-10],
       [  1.00000000e+00,   2.37985087e-13,   2.24263303e-13,
          2.06856938e-13,   5.80743271e-14],
       [  1.00000000e+00,   3.82945720e-09,   1.93660107e-15,
          1.26361095e-17,   2.45812927e-19],
       [  1.00000000e+00,   4.90941732e-09,   1.28872057e-09,
          6.51791555e-13,   3.88971001e-13]], dtype=float32), indices=array([[13, 12, 35, 38, 17],
       [42, 41, 40,  6, 12],
       [38, 34,  8,  0,  1],
       [31, 23, 21,  3, 29],
       [38, 34, 32,  3,  8],
       [12, 13, 40, 35, 41],
       [20, 30, 23, 41, 28],
       [10, 42,  9, 16,  7],
       [ 4,  1,  0,  5,  7],
       [ 2,  1,  3,  5,  7],
       [17, 14,  2, 13, 15],
       [11, 30, 27, 19, 21],
       [17, 14, 38, 12,  2],
       [ 0,  4,  8,  1, 16],
       [ 4,  1,  0,  7,  8],
       [18, 27, 26, 25,  0],
       [33, 36, 35, 12, 39],
       [ 1,  0,  2,  4,  5],
       [22, 29, 26, 30, 31],
       [ 9, 10, 16, 35, 23],
       [33, 39, 36, 35, 40],
       [12, 40, 13, 11,  7],
       [14, 13,  0, 17,  4],
       [28,  9, 30, 41, 29],
       [26, 18, 27, 28, 24],
       [ 5,  7,  1,  2,  3],
       [26, 18, 24, 25, 29],
       [25, 14, 18, 29, 22],
       [ 3,  5,  2, 15, 29],
       [26, 24, 18, 29, 25]]))

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the IPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

Project Writeup

Once you have completed the code implementation, document your results in a project writeup using this template as a guide. The writeup can be in a markdown or pdf file.